package com.hqyj.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hqyj.dormitorymanagement.service.IDormitoryService;
import com.hqyj.dormitorymanagement.service.IDormitoryuserService;
import com.hqyj.maintenancemanagement.service.IUsermaintenanceService;
import com.hqyj.system.keys.Keys;
import com.hqyj.system.pojo.SysUser;
import com.hqyj.system.service.ISysUserRoleService;
import com.hqyj.system.service.ISysUserService;
import com.hqyj.thelatemanagement.service.IUserlateService;
import com.hqyj.utile.PojoUtil;
import com.hqyj.utile.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author rock
 * @since 2021-11-30
 */
@Controller
@RequestMapping("/sys-user")
public class SysUserController {
    @Autowired
    ISysUserService iSysUserService;

    @Resource
    IUserlateService iUserlateService;
    @Resource
    ISysUserRoleService iSysUserRoleService;
    @Resource
    IDormitoryuserService iDormitoryuserService;



    private static Map<String,String>  autoLogin=new ConcurrentHashMap<>();

    //加载表格数据
   /* @GetMapping("/userList")
    public HashMap<String,Object> listPage(SysUser sysUser){
        return iSysUserService.select(sysUser);
    }*/

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpSession session){
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&isLogin(cookies,session)){
            return "back/hui/index";
        }
        return "login";
    }
    //修改


    @PostMapping("/login")
    public String login2(String username, String password,
                         @RequestParam(defaultValue = "") String online, Model model,
                         String code,HttpSession session,
                         HttpServletResponse response){
        Object code1 = session.getAttribute("code");
        if(!code.equals(code1)){
            model.addAttribute("err","验证码不正确");
            return "login";
        }
        if(iSysUserService.login(username,password)){
            session.setAttribute(Keys.LOGIN_NAME,username);
            if(online.equals("ok")){
                String token = TokenUtil.createToken(username);
                Cookie cookie = new Cookie(Keys.LOGIN_COOKIE,token);
                autoLogin.put(username,token.substring(token.lastIndexOf("@")+1));
                cookie.setMaxAge(60*60*24*7);
                response.addCookie(cookie);
            }
            return "back/hui/index";
        }
        model.addAttribute("err","账号或密码不正确");
        return "login";
    }

    @GetMapping("logout")
    public String logout(HttpServletRequest request,HttpSession session){
        session.removeAttribute(Keys.LOGIN_NAME);
        Cookie[] cookies = request.getCookies();
        Optional.ofNullable(cookies).ifPresent(this::removeCookie);
        return "login";
    }

    @PostMapping("confirm")
    @ResponseBody
    @Transactional
    public String delConfirm(Integer userId){
        SysUser user = iSysUserService.getById(userId);
        iSysUserService.removeById(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_id", user.getUserId());
        iDormitoryuserService.removeByMap(map);
        iSysUserRoleService.removeByMap(map);
        iUserlateService.removeByMap(map);
        System.out.println("----成功删除----");
        autoLogin.remove(user.getUsername());
        return "succeed";
    }


    @GetMapping("confirm")
    public String confirm(Model model,
                          @RequestParam(defaultValue = "1") Integer currentPage,
                          @RequestParam(defaultValue = "5")Integer size,
                          @RequestParam(required = false) String search){
        List<SysUser> sysUsers = iSysUserService.queryList(currentPage, size, search);
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        QueryWrapper<SysUser> sate = wrapper.eq("state", "1");
        int count=0;
        if(search!=null&&search!="") {
            QueryWrapper<SysUser> eq = wrapper.eq(Keys.LOGIN_NAME, search);
            count= iSysUserService.count(eq);
        }else {
            count=iSysUserService.count(sate);
        }
        model.addAttribute("pages",sysUsers);
        model.addAttribute("total",count);
        model.addAttribute("currentPage",currentPage);
        return "back/hui/de_list";
    }


    @GetMapping("del")
    public String del(){
        return "back/hui/del_user";
    }

    @PostMapping("del")
    @ResponseBody
    public String del2(String password,String coed,HttpSession session){
        Object username = session.getAttribute(Keys.LOGIN_NAME);
        System.out.println(username);
        System.out.println((PojoUtil.notNull(password,coed,username)));
        if(PojoUtil.notNull(password,coed,username)){
            if(coed.equals(session.getAttribute("code"))) {
                Boolean login = iSysUserService.login(username.toString(), password);
                if (login) {
                    UpdateWrapper<SysUser> wrapper = new UpdateWrapper<>();
                    wrapper.set("state","1").eq(Keys.LOGIN_NAME,username.toString());
                    boolean update = iSysUserService.update(wrapper);
                    if(update){
                        return "succeed";
                    }
                }
            }
        }
        return "fail";
    }

    private void removeCookie(Cookie[] cookies){
        for(Cookie cookie:cookies){
            if(cookie.getName().equals(Keys.LOGIN_COOKIE)){
                cookie.setMaxAge(0);
                return;
            }
        }
    }

    private boolean isLogin(Cookie[] cookies,HttpSession session){
        for(Cookie cookie:cookies){
            if(cookie.getName().equals(Keys.LOGIN_COOKIE)){
                String value = cookie.getValue();
                String[] split = value.split("[@]");
                if(split.length==2){
                    String token = autoLogin.get(split[0]);
                    if(token!=null&&token.equals(split[1])){
                        session.setAttribute(Keys.LOGIN_NAME,split[0]);
                        return true;
                    }
                }
            }
        }
        return false;
    }



}

